﻿using System.IO;
using LitJson;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

public static class FileToolKit
{
    /// <summary>
    /// 从StreamAssets中读取Json文件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static T ReadJsonFile<T>(string filePath, FilePathType pathType)
    {
        if(pathType == FilePathType.Resources)
        {
            var strData = Resources.Load<TextAsset>(filePath);
            return JsonMapper.ToObject<T>(strData.text);
        }
        else
        {
            var strData = File.ReadAllText(filePath + ".json", Encoding.UTF8);
            return JsonMapper.ToObject<T>(strData);
        }
    }


    public static List<string> CoutineCheck(string path)   //是文件夹，继续向下
    {
        List<string> fileName = new List<string>();

        DirectoryInfo directory = new DirectoryInfo(@path);
        if (!directory.Exists) return fileName;
        FileSystemInfo[] fileSystemInfos = directory.GetFileSystemInfos();

        foreach (var item in fileSystemInfos)
        {
            int idx = item.ToString().LastIndexOf(@"\");//得到最后一个'\'的索引
            string name = item.ToString().Substring(idx + 1);//截取后面的作为名称

            if (!name.Contains(".meta"))
            {
                fileName.Add(name.Substring(0, name.LastIndexOf("X")));
            }
        }
        return fileName;
    }

    /// <summary>
    /// 判断文件是否存在，不存在就创建
    /// </summary>
    /// <param name="filePath">文件的绝对路劲，带后缀</param>
    public static void CheckAndCreateFile(string filePath)
    {
        int idx = filePath.LastIndexOf(@"\");//得到最后一个'\'的索引
        string folderPath = filePath.ToString().Substring(0, idx);//截取后面的作为名称

        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
        if(!File.Exists(filePath))
        {
            var file = File.Create(filePath);
            file.Dispose();
        }
    }
}

public enum FilePathType
{
    Resources,
    Streamings
}
